(function (Vue) { //依赖全局的VUE
	const todoList = []
	const TODO_KEY = "todos"
	const todosStorage = {
		fetch() {
			return JSON.parse(localStorage.getItem(TODO_KEY) || '[]')
		},
		set(value) {
			localStorage.setItem(TODO_KEY, JSON.stringify(value))
		}
	}
	Vue.directive("app-focus", {
		inserted: function (el, binding) {
			el.focus()
		},
		update(el, binding) {
			if (binding.value) {
				el.focus()
			}
		},
	})
	var vm = new Vue({
		el: "#todoapp",
		data: {
			title: "todos", //todos
			// todoList,
			todoList: todosStorage.fetch(),
			currentItem: null,
			filterStatus: "all"
		},
		directives: {
			"todo-focus": {
				update(el, binding) {
					if (binding.value) {
						el.focus()
					}
				}
			}
		},
		methods: {
			addTodo: function (e) {
				if (e.target.value.trim() === "") {
					return
				}
				this.todoList.push({ id: this.todoList.length + 1, content: e.target.value, completed: false })
				e.target.value = ""
			},
			delTodo(index) {
				this.todoList.splice(index, 1)
			},
			cleanAllCompleted() {
				// this.todoList.filter(todo =>{
				// 	todo.completed
				// })
				this.todoList = this.todoList.filter(todo => !todo.completed)

			},
			toEdit(todo, event) {
				console.log("toEdit:", todo)
				this.currentItem = todo
			},
			cancelEdit() {
				console.log("cancelEdit:", this.currentItem)
				this.currentItem = null
			},
			commiteEdit(todo, index, event) {
				console.log("commiteEdit:", event.target.value)
				const content = event.target.value.trim()
				if (content === "") {
					this.delTodo(index)
					return
				}
				todo.content = content
				this.currentItem = null
			}
		},
		computed: {
			filterTodoList() {
				switch (this.filterStatus) {
					case "active":
						return this.todoList.filter(todo => !todo.completed)
					case "completed":
						return this.todoList.filter(todo => todo.completed)
					default:
						return this.todoList
				}
			},
			leftTodos() {
				const lefts = this.todoList.filter(function (todo) {
					// return todo.completed === false
					return !todo.completed
				})
				return lefts.length
			},
			toggleAll: {
				get: function () {
					console.log("toggleAll get:", this.leftTodos)
					return this.leftTodos === 0
				},
				set(newValue) {
					console.log("toggleAll set newValue:", newValue)
					this.todoList.forEach((todo) => {
						todo.completed = newValue
					})
				}
			}
		},
		watch: {
			todoList: {
				deep: true,
				handler: function (newValue, oldValue) {
					console.log("watch:", newValue)
					todosStorage.set(newValue)
				}
			}
		}
	})
	window.onhashchange = function () {
		console.log("window.onhashchange:host", window.location.host)
		// #/active   window.location.hash.substr(2) = active
		console.log("window.onhashchange hash:", window.location.hash)
		vm.filterStatus = window.location.hash.substr(2) || 'all'
	}
	window.onhashchange()

})(Vue);
